package org.example.sbringboot1_12.controller;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/header")
public class HeaderController {
//获取Cookie
    @RequestMapping("/getCookie")
    public String getCookie(HttpServletRequest request){
        Cookie[] cookies=request.getCookies();
        for(Cookie cookie:cookies){
            System.out.println(cookie.getName()+":"+cookie.getValue());
        }
        return "获取cookie成功";
    }
    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue("zhuiyi") String zhuiyi){
        return "从Cookie中获取信息，zhuiyi:"+zhuiyi;
    }
    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute("userName","zhuiyi");
        session.setAttribute("age",15);
        return "设置session成功";
    }
    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request){
        HttpSession session = request.getSession();
        String userName = (String) session.getAttribute("userName");
        Integer age = (Integer) session.getAttribute("age");
        return "获取session成功，userName:"+userName+",age:"+age;
    }
    @RequestMapping("/getSession2")
    public String getSession2(HttpSession session){
        String userName = (String) session.getAttribute("userName");
        Integer age = (Integer) session.getAttribute("age");
        return "获取session成功，userName:"+userName+",age:"+age;
    }
    @RequestMapping("/getSession3")
    public String getSession3(@SessionAttribute("userName") String userName){
        return "获取session成功，userName:"+userName;
    }
    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request) {
        String header = request.getHeader("User-Agent");
        return "userAgent"+header;
    }
    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("User-Agent")String userAgent){
        return "userAgent:"+userAgent;
    }
}
